<?
require_once($r."_config/db.php");
require_once($r."_config/site.php");
require_once($r."_engine/c_sql_table.php");

$g_st_plan = new CSqlTable("accounts", "id");

class CPlan
{
	var $id, $data;
	
	function CPlan($id = 0)
	{
		if ($id > 0)
		{
			$this->LoadById($id);
		}
	}
	
	function CreateNew()
	{
		//TODO: take example from CAccount class
	}
	
	function InitNew()
	{
		//TODO: take example from CAccount class
	}
	
	function ReadRegInfoFromForm()
	{
		//TODO: take example from CAccount class
	}
	
	
	function LoadById($id)
	{
		return $this->LoadByQuery(
			"SELECT * FROM plans WHERE id='$id';"
		);
	}
	function LoadByQuery($query)
	{
		global $g_st_plan;
		$row = $g_st_plan->SelectRow($query);
		if (!$row) return false;
		$this->LoadFromArray($row);
		return true;
	}
	
	function LoadFromArray($row)
	{
		foreach($row as $f => $v)
		{
			if (is_int($f)) continue;
			
			if ($f == "id")
				$this->id = $v;
			else
				$this->data[$f] = $v;
		}
	}
	
	function Update($values)
	{
		global $g_st_plan;
		$this->LoadFromArray($values);
		return $g_st_plan->Update($values, $this->id);
	}

	function GetPeriod()
	{
		$r = "";
		$r["L"] = $this->data["period"];
		$r["T"] = $this->data["period_units"];
		return $r;
	}
	function GetPeriodL()
	{
		$r = $this->GetPeriod();
		return isset($r["L"]) ? $r["L"] : "";
	}
	function GetPeriodT()
	{
		$r = $this->GetPeriod();
		return isset($r["T"]) ? $r["T"] : "";
	}
	function GetPeriodText()
	{
		$p = $this->GetPeriod();
		if ($p == "") return "";
		if ($p["L"] == "") return "";
		
		$r = $p["L"] . " ";
		
		switch ($p["T"])
		{
			case "D": $r .= "Day"; break;
			case "W": $r .= "week"; break;
			case "M": $r .= "Month"; break;
			case "Y": $r .= "Year"; break;
		}
		
		return $r;
	}
	
	static function GetInvoice($plan, $account, $period, $units)
	{
		$invoice = $plan."_".$account."_".$period."_".$units."_".date("Y-m-d",time());
		return $invoice;
	}
	

	static function GetPlans()
	{
		$q = "SELECT * FROM plans WHERE active=1 ORDER BY cost ASC, id DESC;";
	
		global $g_st_plan;
		$rows = $g_st_plan->SelectRows($q);
		
		$results = array();
		
		foreach ($rows as $k => $v)
		{
			$n = new CPlan();
			$n->LoadFromArray($v);
			$results[] = $n;
		}
		
		return $results;
	}
}
?>